package com.xbongbong.paas.help.optional.range.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FilterConditionsPoJo;
import com.xbongbong.paas.help.optional.range.UserDeptOptionalRangeHandler;
import com.xbongbong.paas.pojo.dto.UserInfoDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.enums.businessrule.enums.RuleValueTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.domain.entity.ProductUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * @author sunshaoxiang
 * @Description 成员姓名条件过滤
 * @date 2021/9/9 10:10
 * @Version 1.0
 */
public class UserNameHandlerImpl implements UserDeptOptionalRangeHandler {
    private static final Logger LOG = LoggerFactory.getLogger(UserNameHandlerImpl.class);

    @Override
    public Map<String, Object> filterDeptUserData(FilterConditionsPoJo filterConditionsPoJo, JSONObject optionalRangeDataList, PaasFormDataEntity paasFormDataEntity, Map<Integer, List<UserTeamEntity>> userTeam, List<ProductUserEntity> productUserEntityList, UserInfoDTO loginUserInfo) throws XbbException {
        List<String> userIdIn = null;
        List<String> userIdNoIn = null;
        HashMap<String, Object> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //获取当前登录用户信息
        UserVO loginUser = loginUserInfo.getLoginUser();
        Integer valueType = filterConditionsPoJo.getValueType();
        //判断过滤条件类型
        String symbol = filterConditionsPoJo.getSymbol();
        boolean conditionSymbol = true;
        RuleValueTypeEnum ruleValueTypeEnum = RuleValueTypeEnum.getByType(valueType);
        try {
            if (Objects.equals(ConditionEnum.NOIN.getSymbol(), symbol)) {
                conditionSymbol = false;
                userIdNoIn = new ArrayList<>();
            }else {
                userIdIn = new ArrayList<>();
            }
            switch (ruleValueTypeEnum) {
                //处理动态值
                case DYNAMIC_VALUE:
                    //动态值字段为当前登录部门
                    if (Objects.equals(filterConditionsPoJo.getValueFieldType(), FieldTypeEnum.REGISTER_USER.getType())) {
                        String userId = loginUser.getUserId();
                        if (conditionSymbol) {
                            userIdIn.add(userId);
                        } else {
                            userIdNoIn.add(userId);
                        }
                        //动态值字段
                    } else {
                        String dynamicAttr = filterConditionsPoJo.getValueAttr();
                        if (Objects.equals(filterConditionsPoJo.getValueFieldType(), FieldTypeEnum.USER.getType())) {
                            String userId = "";
                            if (Objects.nonNull(optionalRangeDataList)){
                                HashMap user = (HashMap) optionalRangeDataList.get(dynamicAttr);
                                if (Objects.nonNull(user)){
                                    userId = String.valueOf(user.get("id"));
                                }
                            //前端无法传参，从后端取值
                            }else {
                                    userId =String.valueOf(paasFormDataEntity.getData().get(dynamicAttr));
                            }
                            if (StringUtil.isNotEmpty(userId)){
                                if (conditionSymbol) {
                                    userIdIn.add(userId);
                                } else {
                                    userIdNoIn.add(userId);
                                }
                            }
                            //创建人
                        } else if (Objects.equals(filterConditionsPoJo.getValueFieldType(), FieldTypeEnum.CREATORID.getType())){
                            String userId = "";
                            if (Objects.nonNull(paasFormDataEntity) && Objects.nonNull(paasFormDataEntity.getCreatorId())){
                                userId = paasFormDataEntity.getCreatorId();
                                //新建表单时 创建人就是当前登陆人
                            } else {
                                userId = loginUser.getUserId();
                            }
                            if (StringUtil.isNotEmpty(userId)){
                                if (conditionSymbol) {
                                    userIdIn.add(userId);
                                } else {
                                    userIdNoIn.add(userId);
                                }
                            }
                        }else {
                            if (Objects.nonNull(optionalRangeDataList)){
                               List<LinkedHashMap> users = (List) optionalRangeDataList.get(dynamicAttr);
                                if (CollectionsUtil.isNotEmpty(users)){
                                    for (LinkedHashMap user : users) {
                                        String userId = String.valueOf(user.get("id"));
                                        if (conditionSymbol) {
                                            userIdIn.add(userId);
                                        } else {
                                            userIdNoIn.add(userId);
                                        }
                                    }
                                }
                            //前端无法传参，从后端取值
                            }else {
                                 List<UserTeamEntity> users = new ArrayList<>();
                                 //负责人
                                 if (Objects.equals(dynamicAttr, FieldTypeEnum.OWNERID.getAlias())){
                                     //区分负责人团队和可见人
                                     if (Objects.nonNull(userTeam) && userTeam.size() != 0){
                                         users = userTeam.get(1);
                                     }else {
                                         if (conditionSymbol) {
                                             userIdIn.add(paasFormDataEntity.getOwnerId());
                                         } else {
                                             userIdNoIn.add(paasFormDataEntity.getOwnerId());
                                         }
                                     }
                                 //协同人
                                }else if (Objects.equals(dynamicAttr, FieldTypeEnum.COUSERID.getAlias())){
                                     if (Objects.nonNull(userTeam) && userTeam.size() != 0){
                                         users = userTeam.get(0);
                                     }
                                }else {
                                    List<String> userIds = JSONArray.parseArray(JSON.toJSONString(paasFormDataEntity.getData().get(dynamicAttr)), String.class);
                                    if (CollectionsUtil.isNotEmpty(userIds)){
                                        for (String userId : userIds) {
                                            if (conditionSymbol) {
                                                userIdIn.add(userId);
                                            } else {
                                                userIdNoIn.add(userId);
                                            }
                                        }
                                    }
                                }
                                if (CollectionsUtil.isNotEmpty(users)){
                                    for (UserTeamEntity user : users){
                                        if (conditionSymbol){
                                            userIdIn.add(user.getUserId());
                                        }else {
                                            userIdNoIn.add(user.getUserId());
                                        }
                                    }
                                }
                            }
                        }
                    }
                    break;
                //处理固定值
                case FIXED_VALUE:
                    List<ReturnUserAndDepartmentPojo> userList = JSON.parseArray(JSON.toJSONString(filterConditionsPoJo.getValue()), ReturnUserAndDepartmentPojo.class);
                    if (CollectionsUtil.isNotEmpty(userList)){
                        for (int i = 0; i < userList.size(); i++) {
                            ReturnUserAndDepartmentPojo userAndDepartmentPojo = userList.get(i);
                            String userId = String.valueOf(userAndDepartmentPojo.getId());
                            if (conditionSymbol) {
                                userIdIn.add(userId);
                            } else {
                                userIdNoIn.add(userId);
                            }

                        }
                    }
                    break;
                default:
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            userMap.put("userIdIn", userIdIn);
            userMap.put("userIdNoIn", userIdNoIn);
        } catch (XbbException e) {
            LOG.error("UserNameHandlerImpl.filterDeptUserData 执行错误", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return userMap;
    }
}











